package com.lwd.spring.study.bean;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * @Author: 刘东（挂兰）
 * @Date: 2023/12/12 22:32:34
 * @Description:
 */
public class MyPublishBean implements ApplicationEventPublisherAware {
    private ApplicationEventPublisher applicationEventPublisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }

    public void doSomething() {
        // 发布事件
        applicationEventPublisher.publishEvent(new MyEvent(new MyBean(), "event data"));
        // ...
    }
}

/**
 * 监听事件
 */
@Component
class MyEventListener implements ApplicationListener<MyEvent> {
    @Override
    public void onApplicationEvent(MyEvent event) {
        // 处理事件
        // ...
    }
}


class MyEvent extends ApplicationEvent {
    private MyBean myBean;
    private String data;

    public MyEvent(MyBean myBean, String data) {
        super(myBean);
        this.myBean = myBean;
        this.data = data;
    }
}


